package org.goyo.main.services.system.impl;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.goyo.common.utils.DateUtils;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.dao.base.IBillNumberDao;
import org.goyo.main.domain.entity.base.BillNumber;
import org.goyo.main.services.system.IBillNumberService;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class BillNumberServiceImpl implements IBillNumberService{
	@Resource
	private IBillNumberDao billNumberDao;
	
//	/**
//	 * 修改编号
//	 */
//	@Override
//	public synchronized void alterBillNumber(String biztype, String number) {
//		BillNumber bill = new BillNumber();
//		bill.setBiztype(biztype);
//		bill.setNumber(number);
//		billNumberDao.saveOrUpdate(bill);
//	}

	/**
	 * 获得单据编号
	 */
	@Override
	public synchronized String getBillNumber(String biztype) {
		BillNumber  bill = billNumberDao.get(BillNumber.class, biztype);
		String dateNumber = DateUtils.getDateNumber();
		String billNumber = null;
		if(bill != null){
		    String number = bill.getNumber();
			if(number.indexOf(dateNumber) > 0){
				billNumber = ToolUtils.addBillNumber(number,biztype);
			}else{
				billNumber = biztype + dateNumber + "000001";
			}
			bill.setNumber(billNumber);
		}else{
			billNumber = biztype + dateNumber + "000001";
			bill = new BillNumber(); 
			bill.setBiztype(biztype);
			bill.setNumber(billNumber);
		}
		
		billNumberDao.saveOrUpdate(bill);

		return billNumber;
	}

	@Override
	public synchronized String getBaseNumber(String biztype) {
		BillNumber bill = billNumberDao.get(BillNumber.class, biztype);
		String billNumber = null;
		if(bill != null){
		    String number = bill.getNumber();
			billNumber = ToolUtils.addBaseNumber(number,biztype);
			bill.setNumber(billNumber);
		}else{
			billNumber = biztype + "000001";
			bill = new BillNumber(); 
			bill.setBiztype(biztype);
			bill.setNumber(billNumber);
		}
		billNumberDao.saveOrUpdate(bill);
		return billNumber;
	}
}
